use std::path::Path;

use axum::Json;
use serde_json::Value;

use crate::code;

pub fn get_rel_path(path:&str) -> String {
    if path.starts_with("./") { path.to_owned() } else { format!("./{}", path) }
}
pub fn get_parent_path_str(path:&str) -> Result<String, Json<Value>> {
    if let Some(f) = Path::new(&path).parent() {
        Ok( f.to_str().unwrap_or_default().to_owned() )
    }else {
        Err(code::err_(format!("【{}】的父路径不存在", path)))
    }
}

pub fn get_suffix( filename:String ) -> Option<String>{
    let path = std::path::Path::new(&filename);
    path.extension().map(|ext| ext.to_str().unwrap()).and_then(|v| Some(v.to_string()))
}
// 判断文件是否存在
pub fn exist(path:&str) -> Result<bool, Json<Value>>{
    let path = Path::new(&path);
    match path.try_exists() {
        Ok(f) => {
            Ok(f)
        },
        Err(e) => {
            Err( code::err_(e.to_string()))
        }
    }
}
pub fn exist_not_err(path:&str) -> Result<Json<Value>, Json<Value>>{
    let str = if let Some(_) = Path::new(&path).file_name() { "" } else { "目录" };
    if exist(&path)? {
        code::ok()
    }else{
        return code::err(format!("文件{}【{}】不存在", str, path))
    }
}
pub fn exist_err(path:&str) -> Result<Json<Value>, Json<Value>>{
    let str = if let Some(_) = Path::new(&path).file_name() { "" } else { "目录" };
    if exist(&path)? {
        return code::err(format!("文件{}【{}】已存在，不允许操作", str, path))
    }else{
        code::ok()
    }
}
pub fn exist_rel(path:&str) -> Result<bool, Json<Value>>{ exist(&get_rel_path(path)) }

// 获取文件后缀类型
pub fn get_file_type(file_name:&str ) -> String{
    let path = std::path::Path::new(&file_name);
    // path.extension().map(|ext| ext.to_str().unwrap()).unwrap_or_default().to_string()
    path.extension().unwrap_or_default().to_str().unwrap_or_default().to_string()
}
// 获取文件名
pub fn get_file_name(file_name:&str ) -> String{
    let path = std::path::Path::new(&file_name);
    path.file_stem().unwrap_or_default().to_str().unwrap_or_default().to_string()
}